#include "keeptokenlive.h"
#include "services/yingceservice.h"
#include "usersettings.h"
#include <QDateTime>
#include <QTimer>

KeepTokenLive::KeepTokenLive(QObject* parent) : QObject { parent }
{
    timer_ = new QTimer(this);
    timer_->stop();
    connect(timer_, &QTimer::timeout, this, &KeepTokenLive::refreshToken);
}

void KeepTokenLive::start()
{
    QDateTime now = QDateTime::currentDateTime();
    qint64 msecs = now.msecsTo(UserSettings::instance().loginUser().accessTokenExpire()) - 10000;
    if (msecs < 0) {
        if (UserSettings::instance().loginUser().refreshTokenExpire() >= now) {
            refreshToken();
        }
    } else {
        timer_->start(msecs);
    }
}

void KeepTokenLive::stop()
{
    timer_->stop();
}

void KeepTokenLive::refreshToken()
{
    YingCeService::instance()->refreshToken(
            UserSettings::instance().loginUser().refreshToken(),
            yc::ResponseHandler(this,
                                [this](const yc::Request& request, const yc::Response& response) {
                                    Q_UNUSED(request)
                                    if (response.status() == yc::OK_CODE) {
                                        yc::LoginUser& user = UserSettings::instance().loginUser();
                                        user.updateData(response.data().toObject());
                                        YingCeService::instance()->setAuthentication(
                                                user.accessToken(), user.refreshToken());
                                        start();
                                    } else {
                                        stop();
                                        Q_EMIT tokenExpired();
                                    }
                                }));
}
